package com.qcs.sleep.call;

import org.json.JSONException;
import org.json.JSONObject;

import java.util.Observable;
import java.util.Observer;

/**
 * Created by chshqiang on 15-7-21.
 * 用于通知所有的 Observer
 */
public class PushChanger extends Observable {
    private static final PushChanger PUSH_CHANGER = new PushChanger();

    private PushChanger() {
    }

    public static PushChanger getInstance() {
        return PUSH_CHANGER;
    }

    public void send(String push) {
        PushCaller caller = new PushCaller();

        try {
            JSONObject jo = new JSONObject(push);
            caller.setType(Integer.valueOf(jo.get("type").toString()));
            caller.setAction(Integer.valueOf(jo.get("action").toString()));
            caller.setContent(jo.get("content").toString());
            caller.setSender(jo.get("sender").toString());
        } catch (JSONException e) {
            e.printStackTrace();
        }

        send(caller);
    }

    private void send(PushCaller caller) {
        setChanged();
        notifyObservers(caller);
    }

    @Override
    public void addObserver(Observer observer) {
        if (observer instanceof PushWatcher)
            super.addObserver(observer);
    }

    @Override
    public synchronized void deleteObserver(Observer observer) {
        if (observer instanceof PushWatcher)
            super.deleteObserver(observer);
    }
}
